package xkp.lesson.store.activity.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.theartofdev.edmodo.cropper.CropImage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import xkp.lesson.store.Config;
import xkp.lesson.store.R;
import xkp.lesson.store.entity.MessageEvent;
import xkp.lesson.store.utils.HttpUtils;

public class AddBuildFragment extends Fragment {

    private EditText deviceNameEdit,deviceLocationEdit,descriptionEdit;
    private ImageView buildImage;
    private Button submitBtn;
    private Uri imageUri, resultUri;
    private File mOutputImage;
    private Bitmap mBitmap;
    public static final int TAKE_PHOTO = 1;
    public static final int CUT_PHOTO = 2;



    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_addbuild, container, false);
        EventBus.getDefault().register(this);
        deviceNameEdit = root.findViewById(R.id.deviceName);
        deviceLocationEdit = root.findViewById(R.id.deviceLocation);
        descriptionEdit = root.findViewById(R.id.description);
        buildImage = root.findViewById(R.id.buildimg);
        submitBtn = root.findViewById(R.id.submitBtn);

        buildImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOutputImage = new File(getActivity().getExternalCacheDir(), "output_image.jpg");

                try {
                    if (mOutputImage.exists()) {
                        mOutputImage.delete();
                    }
                    boolean flag = mOutputImage.createNewFile();
                    Log.e("flag",flag+"");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (Build.VERSION.SDK_INT >= 24) {
                    imageUri = FileProvider.getUriForFile(getActivity()
                            , "xkp.lesson.store.fileprovider",
                            mOutputImage);
                } else {
                    imageUri = Uri.fromFile(mOutputImage);
                }
                //启动相机程序
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, TAKE_PHOTO);
            }
        });

        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File file = null;
                OkHttpClient client = HttpUtils.getClient();
                try {
                    file = new File(new URI(resultUri.toString()));
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                RequestBody body = RequestBody.create(MediaType.parse("image/png"), file);

                MultipartBody.Builder builder = new MultipartBody.Builder();
                builder.setType(MultipartBody.FORM);
                builder.addFormDataPart("buildImg", System.currentTimeMillis()+".jpg", body);
                builder.addFormDataPart("deviceName", deviceNameEdit.getText().toString());
                builder.addFormDataPart("deviceLocation", deviceLocationEdit.getText().toString());
                builder.addFormDataPart("description", descriptionEdit.getText().toString());
                MultipartBody multipartBody = builder.build();

                Request request = new Request.Builder()
                        .url(Config.BASE_URL+"/building/saveBuild")
                        .post(multipartBody)
                        .addHeader("token", Config.token)
                        .build();

                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String s = response.body().string();
                        Log.e("MainActivity", s);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "成功" + s, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
            }
        });

        return root;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        buildImage.setImageBitmap((Bitmap) messageEvent.getData());
        resultUri = messageEvent.getResultUri();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        Log.i("AddBuildFragment",requestCode+"");

        switch (requestCode) {

            case TAKE_PHOTO:
                if (resultCode == getActivity().RESULT_OK) {
                    CropImage.activity(imageUri)
                            .start(getActivity());
                }
                break;
            case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE: {

                CropImage.ActivityResult result = CropImage.getActivityResult(data);
                if (resultCode == getActivity().RESULT_OK) {
                    resultUri = result.getUri();
                    try {
                        mBitmap = BitmapFactory.decodeStream(
                                getActivity().getContentResolver().openInputStream(resultUri));
                        buildImage.setImageBitmap(mBitmap);
                        Log.i("AddBuildFragment","----------------");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                    Exception error = result.getError();
                }
            }
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}